package manager.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import manager.utils.FileOperateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.Socket;

/**
 * @author shidang.hu
 */
public class HandlerFileProcessor implements Runnable {

    private Logger logger = LoggerFactory.getLogger(HandlerFileProcessor.class);
    private static final String FILE_PATH = "filePath";
    private static final String FILE_OPERATION = "operation";
    private static final String FILE_UPLOAD = "upload";
    private static final String FILE_DOWNLOAD = "download";

    private Socket sock;
    private String rootPath;
    private String encryptFlag;
    private String encryptKey;

    public HandlerFileProcessor(Socket sock, String rootPath, String encryptFlag,String encryptKey) {
        this.sock = sock;
        this.rootPath = rootPath;
        this.encryptFlag = encryptFlag;
        this.encryptKey = encryptKey;
    }

    /***
     * 如果有路径约定用正斜杠，不要使用反斜杠传文件路径，否则会报错。
     */
    @Override
    public void run() {
        //获取客户端ip
        String ip = sock.getInetAddress().getHostAddress();
        logger.info("客户端IP: {} 到访", ip);
        FileOutputStream fos = null;
        DataInputStream dis = null;
        try {
            //定义socket输入流,接收客户端的信息,接受客服端发来的文件
            dis = new DataInputStream(sock.getInputStream());
            //文件名和长度
            String jsonMsg = dis.readUTF();
            // 文件长度这一步必须执行，否则文件打不开
            long fileLength = dis.readLong();

            // 解析文件相关信息
            JSONObject obj = JSON.parseObject(jsonMsg);
            String act = obj.getString(FILE_OPERATION);
            String fileFullPath = obj.getString(FILE_PATH);
            fileFullPath = rootPath + fileFullPath;

            if (FILE_UPLOAD.equals(act)) {
                // 上传
//                boolean uploadFlag = FileOperateUtils.processUpload(fileFullPath, fos, dis);
                boolean uploadFlag = FileOperateUtils.HandleUpload(fileFullPath, fos, dis, encryptFlag, encryptKey);
                if (uploadFlag) {
                    logger.info("ip: " + ip + "文件：" + fileFullPath + " 上传完成。");
                }
            } else if (FILE_DOWNLOAD.equals(act)) {
                // 下载
//                boolean downloadFlag = FileOperateUtils.processDownload(fileFullPath, sock);
                boolean downloadFlag = FileOperateUtils.HandleDownload(fileFullPath, sock, encryptFlag, encryptKey);
                if (downloadFlag) {
                    logger.info("ip: " + ip + "文件：" + fileFullPath + " 下载完成。");
                }
            }
        } catch (Exception e) {
            logger.error(ip + "访问系统异常", e);
        } finally {
            try {
                if (dis != null) {
                    dis.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (sock != null || !sock.isClosed()) {
                    sock.close();
                }
            } catch (Exception e) {
                logger.error("socket关流异常", e);
            }
        }
    }

}
